const { get, post } = require('../../utils/request.js')
const { baseUrl } = require('../../utils/config.js')
const { shared, timing, Easing, runOnJS } = wx.worklet;
Page({

  /**
   * 页面的初始数据
   */
  data: {
    baseUrl: baseUrl,
    templateMsgId: [
      'dmBkJ8mESktdLBHS3OhgFxHKX5WDNJZfepomCGUhjKw'
    ],
    showSubscribeContainer: false,
    showCountNontify: false,
    showTipOpenNontify: false,
    tabs: [],
    backgroundImage: '/resoures/remind/topbar1.jpg',
    tabBodyData: [],
    activeIndex: 0,
    currentTab: 'tab0',
    activeTabId: -1,
    pageNubmer: 1,
    triggered: false,
    directionFlag: {},
    fixMoneyData: [],
    fixMoneyAnimal: [],
    isNewUser: false,
    allowCount: 0
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    this.data.directionFlag = shared(0);
    wx.showLoading({
      title: '加载中',
    })

    wx.login({
      success: ({ code }) => {
        post('login/login', { code: code }, ({ token, unicode }) => {
          wx.setStorageSync('token', token)
          wx.setStorageSync('unicode', unicode)
          this.freshData()
        })
      }, fail({ errMsg }) {
        console.log(errMsg)
      }
    })
  },
  showSubscribeMsg() {
    this.setData({
      showTipOpenNontify: true
    })
  },
  hideSubscribeMsg() {
    this.setData({
      showTipOpenNontify: false
    })
  },
  freshData() {
    get('remind/initdata', null, ({ remindTypes, count, taskCount }) => {
      this.setData({
        allowCount: count,
        showCountNontify: count < 5 && taskCount > 0
      })
      if (remindTypes && remindTypes.length > 0) {
        const datas = remindTypes[0].remindTasks;
        const temp = [];

        datas.forEach((item) => {
          temp.push({
            cardX: shared(0),
            deleteX: shared(0),
            modifyX: shared(0),
            copyX: shared(0),
          })
        })

        this.setData({
          activeIndex: 0,
          tabs: remindTypes,
          tabBodyData: [],
          fixMoneyData: datas,
          fixMoneyAnimal: temp,
          triggered: false
        })

        this.spliceArrayDataOnPath(['tabBodyData'], 0, 0, datas);
        this.applyDataUpdates()

        setTimeout(() => {
          this.freshAnnimalData()
        }, 500);

        wx.hideLoading()
      }
    })

    const showSubscribeMsg = this.showSubscribeMsg.bind(this);
    const hideSubscribeMsg = this.hideSubscribeMsg.bind(this);
    const templateMsgId = this.data.templateMsgId;
    wx.getSetting({
      withSubscriptions: true,
      success(res) {
        const { subscriptionsSetting: { mainSwitch, itemSettings } } = res
        if (!mainSwitch) {
          post('login/resetcount')
        }
        if (!mainSwitch || !itemSettings) {
          showSubscribeMsg();
          return;
        } else {
          let flag = true;
          templateMsgId.forEach(item => {
            if (!itemSettings[item] || itemSettings[item] == 'reject') {
              showSubscribeMsg();
              flag = false;
              return;
            }
          })
          if (flag) {
            hideSubscribeMsg();
          }
          return;
        }
      }
    })
  },

  freshAnnimalData() {
    this.data.fixMoneyAnimal.forEach((item, index) => {
      item.cardX.value = 0;
      item.deleteX.value = 0;
      item.modifyX.value = 0;
      item.copyX.value = 0;

      this.applyAnimatedStyle(`.card-index-${index}`, () => {
        'worklet';
        return {
          transform: `translateX(${item.cardX.value}px)`,
        };
      });

      this.applyAnimatedStyle(`.modify-index-${index}`, () => {
        'worklet';
        return {
          transform: `translateX(${item.modifyX.value}px)`,
        };
      });

      this.applyAnimatedStyle(`.copy-index-${index}`, () => {
        'worklet';
        return {
          transform: `translateX(${item.copyX.value}px)`,
        };
      });
    })
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  },
  onClickAdd() {
    wx.navigateTo({
      url: `/pages/remind/remindType/remindType`,
    })
  },
  clickAddRemind() {
    wx.navigateTo({
      url: `/pages/remind/remindForm/remindForm`,
    })
  },
  pageQuery() {
    const pageNumber = this.data.pageNumber;
    const activeTabId = this.data.activeTabId;
    const startIndex = this.data.tabBodyData.length;
    const dataLength = this.data.tabBodyData.length;
    get(`remind/list`, { 'filter_remindType.id_eq_i': activeTabId }, (datas) => {
      this.setData({
        tabBodyData: datas,
        pageNubmer: this.data.pageNubmer + 1
      })
      this.spliceArrayDataOnPath(['tabBodyData'], 0, 0, datas);
      this.applyDataUpdates()
    })
  },
  onTabTap({ currentTarget: { dataset: { index } } }) {
    let bodyData = this.data.tabs[index].remindTasks;
    const temp = [];
    if (bodyData == null) {
      bodyData = []
    }
    bodyData.forEach(() => {
      temp.push({
        cardX: shared(0),
        deleteX: shared(0),
        modifyX: shared(0),
        copyX: shared(0),
      })
    })
    this.setData({
      activeIndex: index,
      tabBodyData: [],
      fixMoneyData: bodyData,
      fixMoneyAnimal: temp
    })
    this.spliceArrayDataOnPath(['tabBodyData'], 0, 0, bodyData);
    this.applyDataUpdates()
    setTimeout(() => {
      this.freshAnnimalData()
    }, 500);

  },

  onCloseTypeItem({ currentTarget: { dataset: { index } } }) {
    const durationTime = 600;
    const animalBezier = Easing.bezier(.16, .53, .18, .82);
    if (this.data.fixMoneyData[index].cardOpened) {
      const child = this.data.fixMoneyAnimal[index];
      this.data.fixMoneyData[index].cardOpened = false
      child.cardX.value = timing(0, {
        duration: durationTime,
        easing: animalBezier,
      });
      child.deleteX.value = timing(0, {
        duration: durationTime,
        easing: animalBezier,
      });
      child.modifyX.value = timing(0, {
        duration: durationTime,
        easing: animalBezier,
      });
      child.copyX.value = timing(0, {
        duration: durationTime,
        easing: animalBezier,
      });
    } else {
      const taskId = this.data.tabBodyData[index].id;
      const remindTypeName = this.data.tabBodyData[index].remindTypeName;

      wx.navigateTo({
        url: `/pages/remind/remindForm/remindForm?id=${taskId}&remindType=${remindTypeName}`,
      })
    }

  },
  onGestureEvent(e) {
    'worklet'
    const { deltaX, state, currentTarget: { dataset: { index } } } = e;

    const child = this.data.fixMoneyAnimal[index];
    const tempX = child.cardX.value + deltaX;
    const cardOpenX = -123;
    const deleteOpenX = -5;
    const copyOpenX = -40;
    const modifyOpenX = -80;
    const durationTime = 600;
    const animalBezier = Easing.bezier(.16, .53, .18, .82);

    if (deltaX > 0) {
      this.data.directionFlag.value = 1;
    } else if (deltaX < 0) {
      this.data.directionFlag.value = -1;
    }

    if (state == 2) {
      if (tempX > 0) {
        child.cardX.value = 0;
        child.deleteX.value = 0;
        child.modifyX.value = 0;
        child.copyX.value = 0;
      } else {
        let calculateX = deltaX;
        if (child.cardX.value < cardOpenX) {
          const n1 = Math.abs(child.cardX.value + deltaX) + cardOpenX;
          calculateX = deltaX * (1 - n1 * 1.0 / 50)
        }

        child.cardX.value += calculateX;
        if (child.deleteX.value + calculateX * 0.7 < deleteOpenX) {
          child.deleteX.value = deleteOpenX
        } else if (child.deleteX.value + calculateX * 0.7 > 0) {
          child.deleteX.value = 0
        } else {
          child.deleteX.value += calculateX * 0.7
        }

        if (child.modifyX.value + calculateX * 0.7 < modifyOpenX) {
          child.modifyX.value = modifyOpenX
        } else if (child.modifyX.value + calculateX * 0.7 > 0) {
          child.modifyX.value = 0
        } else {
          if (deltaX > 0) {
            child.modifyX.value += calculateX * 1.2
          } else {
            child.modifyX.value += calculateX * 0.7
          }

        }

        if (child.copyX.value + calculateX * 0.7 < copyOpenX) {
          child.copyX.value = copyOpenX
        } else if (child.copyX.value + calculateX * 0.7 > 0) {
          child.copyX.value = 0
        } else {
          child.copyX.value += calculateX * 0.7
        }

      }
    } else if (state == 3) {
      if (this.data.directionFlag.value > 0) {
        runOnJS(this.updateFixMoney)(index, false)

        child.cardX.value = timing(0, {
          duration: durationTime,
          easing: animalBezier,
        });
        child.deleteX.value = timing(0, {
          duration: durationTime,
          easing: animalBezier,
        });
        child.modifyX.value = timing(0, {
          duration: durationTime,
          easing: animalBezier,
        });
        child.copyX.value = timing(0, {
          duration: durationTime,
          easing: animalBezier,
        });
      } else {
        runOnJS(this.updateFixMoney)(index, true);

        child.cardX.value = timing(cardOpenX, {
          duration: durationTime,
          easing: animalBezier,
        });

        child.deleteX.value = timing(deleteOpenX, {
          duration: durationTime,
          easing: animalBezier,
        });

        child.modifyX.value = timing(modifyOpenX, {
          duration: durationTime,
          easing: animalBezier,
        });

        child.copyX.value = timing(copyOpenX, {
          duration: durationTime,
          easing: animalBezier,
        });
      }
    }
  },
  initDepositData(data) {
    const deposits = data;
    const temp = []

    deposits.forEach(() => {
      temp.push({
        cardX: shared(0),
        deleteX: shared(0),
        modifyX: shared(0),
        copyX: shared(0),
      })
    })

    this.setData({
      fixMoneyData: deposits,
      fixMoneyAnimal: temp
    })

    this.data.fixMoneyAnimal.forEach((item, index) => {
      item.cardX.value = 0;
      item.deleteX.value = 0;
      item.modifyX.value = 0;
      item.copyX.value = 0;

      this.applyAnimatedStyle(`.card-index-${index}`, () => {
        'worklet';
        return {
          transform: `translateX(${item.cardX.value}px)`,
        };
      });

      this.applyAnimatedStyle(`.modify-index-${index}`, () => {
        'worklet';
        return {
          transform: `translateX(${item.modifyX.value}px)`,
        };
      });

      this.applyAnimatedStyle(`.copy-index-${index}`, () => {
        'worklet';
        return {
          transform: `translateX(${item.copyX.value}px)`,
        };
      });
    })
  },
  updateFixMoney(index, openedFlag) {
    this.data.fixMoneyData[index].cardOpened = openedFlag
  },
  freshAnnimal() {
    this.freshAnnimalData()
  },
  modifyRemind({ currentTarget: { id } }) {
    const taskId = this.data.tabBodyData[id].id;
    const remindTypeName = this.data.tabBodyData[id].remindTypeName;

    wx.navigateTo({
      url: `/pages/remind/remindForm/remindForm?id=${taskId}&remindType=${remindTypeName}`,
    })
  },

  copyRemind({ currentTarget: { id } }) {
    const taskId = this.data.tabBodyData[id].id;
    const remindTypeName = this.data.tabBodyData[id].remindTypeName;

    wx.navigateTo({
      url: `/pages/remind/remindForm/remindForm?id=${taskId}&copy=1&remindType=${remindTypeName}`,
    })
  },

  resetData() {
    this.setData({
      tabBodyData: []
    })
  },
  removeRemind({ currentTarget: { id } }) {
    const taskId = this.data.tabBodyData[id].id;
    const onload = this.onLoad.bind(this);
    const resetData = this.resetData.bind(this);
    const remindTypeName = this.data.tabBodyData[id].remindTypeName;

    wx.showModal({
      title: '提示',
      content: '确定删除？',
      success(res) {
        if (res.confirm) {
          wx.showLoading({
            title: '加载中',
          })
          resetData();
          if (remindTypeName == '生理期') {
            get(`menses/delete/${taskId}`, null, () => {
              onload();
              wx.hideLoading()
            })
          } else {
            get(`remind/deleteRemind/${taskId}`, null, () => {
              onload();
              wx.hideLoading()
            })
          }
        }
      }
    })
  },
  downPullFresh() {
    this.freshData()
  },
  subscribleNotify() {
    this.setData({
      showSubscribeContainer: true
    })
  },
  countNotify() {
    this.goIncrease()
  },
  hideModal() {
    this.setData({ showSubscribeContainer: false });
  },
  goIncrease() {
    wx.navigateTo({
      url: '/pages/remind/increaseCount/increaseCount',
    })
  },
  freshAllowAccount() {
    get('remind/allowcount', null, (count) => {
      this.setData({
        allowCount: count
      })
    })
  },
}) 